<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\bootstrap\Modal;
use kitt2000\ztree\ZTree;
use kitt2000\uploader\Uploader;
use kartik\widgets\ActiveForm;
use common\models\FormVal;
use common\models\goods\GoodsType;
use common\models\goods\GoodsCategory;
use backend\modules\supplier\models\GoodsClass;
use backend\modules\supplier\models\Factory;

/* @var $this yii\web\View */
/* @var $model common\models\goods\Goods */
/* @var $form yii\widgets\ActiveForm */

$def = [0 => '不选择'];
$t = ArrayHelper::map(GoodsType::find()->where(['enable' => 1])->all(), 'id', 'name');
$goodsTypes = array_merge($def, $t);

$t = ArrayHelper::map(Factory::getAll(), 'id', 'name');
$factorys = array_merge($def, $t);

$brands = [];

?>

<style>
    .goodsItem{margin-bottom:20px;}
    .goods-category{padding:4px 8px;max-height:300px;margin-right:20px;}
    
    #gallery_img{width:327px;height:327px;border:#ccc 1px solid;}
    .gallery_progress{display:none;}
    
    .gallery-thumb{width:330px;overflow:hidden;}
    .gallery-thumb .box{width:62px;height:62px;border:#ccc 1px solid;float:left;margin: 6px 2px;position:relative;}
    .gallery-thumb .box:first-child{margin-left:0px;}
    .gallery-thumb .box:last-child{margin-right:0px;}
    .gallery-thumb .box .toolbar{position:absolute;bottom:0px;left:0px;width: 100%;height:20px;display:none;}
    .gallery-thumb .box .toolbar span{float:left;width:33.3%;height:100%;cursor:pointer;}
    
    .uploader{margin:0px;padding:0px;border:0px;width: 326px;}
    .uploader div.browser label{margin:4px 0px;width:100%;box-shadow:none;}
    
    #pack_unit:hover #pack_unit_list{display:block;}
    #pack_unit_list{position:absolute;top:62px;left:0px;margin-left:15px;width:150px;background:#fff;padding-top:2px;padding-bottom:2px;z-index:1000;display:none;}
    #pack_unit_list div{display:block;float:left;cursor:pointer;height:100%;font-weight:bold;font-size:16px;padding:4px;}
    #pack_unit_list div:hover{background:#ddd;}
    
    #attr_img_form{width:0px;height:0px;overflow:hidden;}
    
    .sku-item{clear:both;margin:6px auto;}
    .sku-item li{float:left;width:145px;height:25px;vertical-align: middle;list-style:none;margin:4px auto;}
    .sku-item li label{display: inline-block;}
    .sku-item li label .c_flower{background-position: 0 0;}
    .sku-item li label .c_trans{background-position: 0 -19px;}
    .sku-color{overflow: hidden;width: 14px;height: 14px;display: inline-block;border: 1px solid #E4E4E4;margin-right:2px;}
    .sku-custom-name{width:72px;}
    
    .sku-img{margin-top:15px;}
    table.sku-img-list{background:#C0C0C0;border-collapse:separate;border-spacing: 1px 1px;}
    .sku-img-list th,#product_list th{height: 25px;line-height: 25px;background:#E4E4E4;text-align: center;padding: 2px 8px;}
    .sku-img-list td,#product_list td{background:#fff;padding: 4px;}
    .sku-img-list .thumb{margin-left: 25px;margin-right: 8px;}
    .upload-img-list .thumb img{width: 24px;height: 24px;}

    #product_list table{background:#C0C0C0;border-collapse:separate;border-spacing: 1px 1px;}
    #product_list tr.title{display:table-row;}
    
    .price-step{margin:4px auto;}
    
    #one_product_copy{display:none;}
</style>

<?php $form = ActiveForm::begin([
    'enableClientScript'=>true,
    'options'=>[
        'beforeSubmit' => "function(form){return mySubmitCheck(form);}",
    ],
    ]); ?>

<input type="hidden" name="GoodsForm[id]" value="<?=$model->id?>" />

<?php
$gallery=$model->gallery;

?>

<div class="goods-form col-sm-10">
    <div id="info" class="goodsItem">
        <legend>商品信息</legend>
        <div class="gallery col-sm-3" style="min-width:350px;padding-left:0px;">
            <div id="gallery_img"><img src="<?=!empty($gallery[0]['img'])?Yii::$app->params['urls']['img'].$gallery[0]['img']:''?>" width="325" height="325"></div>
            <div class="gallery-thumb">
                <?php for ($i = 0 ; $i < 5 ; $i ++):?>
                <div class="box">
                    <img src="<?=!empty($gallery[$i]['img'])?Yii::$app->params['urls']['img'].$gallery[$i]['img']:''?>" width="60" height="60" />
                    <div class="toolbar">
                        <span class="left" onclick="galleryMove(<?=$i?>,1);" title="左移"></span>
                        <span class="right" onclick="galleryMove(<?=$i?>,2);" title="右移"></span>
                        <span class="delete" onclick="galleryDel(<?=$i?>);" title="删除"></span>
                    </div>
                </div>
                <input type="hidden" name="GoodsForm[gallery][<?=$i?>][id]" class="gallery-id" value="<?=$gallery[$i]['id']?>" />
                <input type="hidden" class="gallery-thumb-input" name="GoodsForm[gallery][<?=$i?>][img]" value="<?=$gallery[$i]['img']?>" />
                <?php endfor;?>
                <div class="clear"></div>
            </div>
            
            <div id="btn_gallery" class="uploader" style="position:relative;">
                <div class="browser">
                    <label>
                        <span>上传商品相册</span>
                        <input type="file" name="temp[]" multiple="multiple" title='点击添加文件'>
                    </label>
                </div>
                <div id='gallery_mask' class="none" style="position:absolute;width:100%;height:110%;top:0px;left:0px;opacity:0;">a</div>
            </div>
            <?php
            $setting=[
                'url'=>  Url::to(['/upload/temp']),
                'fileName'=>'tempFile',
                'dataType'=>'json',
                'allowedTypes'=>'image/*',
                'extFilter'=>'jpg;png;gif',
                'maxFileSize'=>800*1024,   //800K
                'onFileTypeError'=>new JsExpression('gallery_onFileTypeError'),
                'onFileSizeError'=>new JsExpression('gallery_onFileSizeError'),
                'onUploadSuccess'=>new JsExpression('gallery_onUploadSuccess'),
                'onUploadProgress'=>new JsExpression('gallery_onUploadProgress'),
            ];

            echo Uploader::widget(['id'=>'btn_gallery','setting'=>$setting]); 
            ?>
            <span id="gallery_progress" class="gallery_progress">0%</span>
        </div>
        <div class="col-sm-4">
            <div class="row"><div class="col-sm-12"><?= $form->field($model, 'name')->textInput(['maxlength' => 50]) ?></div></div>
            <div class="row">
                <div class="col-sm-12">
                    <?php
                    $field=$form->field($model, 'category_id');
                    $field->template='{label}{input}<div id="goods_category_content"></div>{hint}{error}';
                    echo $field->hiddenInput() ?>
                    
                    <div id="goods_category_content_copy" style="display:none;">
                        <span id="goods_category_list" style="margin-right:6px;">
                            <?php
                             if($model->category_id>0){
                                 $category = GoodsCategory::findOne($model->category_id);
                                 if($category){
                                     $parents=$category->getRoute();
                                     foreach ($parents as $item) {
                                         echo $item->name.' >> ';
                                     }
                                 }
                                 echo $category->name;
                             }
                            ?>
                        </span>
                        <?php
                        Modal::begin([
                            'id' => 'selectGoodsCategoryDialog',
                            'header' => '<b style="font-size:16px;">请选择商品类目</b>',
                            'toggleButton' => ['label' => '选择', 'class' => 'btn', 'id' => 'btn-create'],
                            'footer' => Html::Button('选择类目', ['class' => 'btn btn-primary', 'id' => 'btn-category-affirm', 'onclick' => 'selectGoodsCategory();']),
                        ]);
                        ?>

                        <div class="goods-category-content">
                            <?php
                            $root = ArrayHelper::map(GoodsCategory::getList(), 'id', 'name');
                            echo Html::dropDownList('GoodsForm[category][]', 0, $root, ['multiple' => 'multiple', 'class' => 'goods-category']);
                            ?>
                        </div>

                        <?php
                        Modal::end();
                        ?>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="form-group field-goods-class_id">
                        <label class="control-label" for="goods-class_id">分类</label>
                        <input type="hidden" id="goodsform-class_id" class="form-control" name="GoodsForm[class_id]" value="<?= $model->class_id ?>">
                        <div>
                            <span id="goods_class_list" style="margin-right:6px;max-height:600px;">
                                <?php
                                if(!empty($model->class_id)){
                                    $classIds = explode(',', $model->class_id);
                                    $class = GoodsClass::findAll($classIds);
                                    $con='';
                                    foreach ($class as $item) {
                                        echo $con.$item->name;
                                        $con='，';
                                    }
                                }
                                ?>
                            </span>
                            <?php
                            Modal::begin([
                                'id' => 'selectGoodsClassDialog',
                                'header' => '<b style="font-size:16px;">请选择自定义分类</b>',
                                'toggleButton' => ['label' => '选择', 'class' => 'btn', 'id' => 'btn-create'],
                                'footer' => Html::Button('选择分类', ['class' => 'btn btn-primary', 'id' => 'btn-class-affirm', 'onclick' => 'closeGoodsClassDialog();']),
                            ]);
                            ?>

                            <div class="goods-class-content">
                                <?php
                                    $setting=[
                                        'check'=>[
                                            'enable'=>true,
                                            'chkboxType'=>['Y'=>'','N'=>''],
                                        ],
                                        'view'=>[
                                            'dblClickExpand'=>false
                                        ],
                                        'data'=>[
                                            'simpleData'=>['enable'=>true],
                                        ],
                                        'callback'=>[
                                            'beforeClick'=>new JsExpression('beforeClick'),
                                            'onCheck'=>new JsExpression('onCheck'),
                                        ],
                                    ];
                                    
                                    $class = GoodsClass::getTree();
                                    $nodes=getList($class,explode(',', $model->class_id));

                                    echo ZTree::widget(['id'=>'tree_class_id','setting'=>$setting,'nodes'=>$nodes]); 
                                ?>
                            </div>

                            <?php
                            Modal::end();
                            ?>
                        </div>
                        <div class="help-block"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-4"><?= $form->field($model, 'goods_type')->dropDownList($goodsTypes) ?></div>
                <div class="col-sm-4"><?= $form->field($model, 'brand_id')->dropDownList($brands) ?></div>
                <div class="col-sm-4" style="position:relative;" id="pack_unit">
                    <?= $form->field($model, 'pack_unit')->textInput(['maxlength' => 8]) ?>
                    <div id="pack_unit_list"></div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-sm-6"><?= $form->field($model, 'is_on_sale')->radioList([1 => '上架',0 => '下架'], ['separator' => FormVal::$separator10]); ?></div>
                <div class="col-sm-6"><?= $form->field($model, 'is_stock_disable')->radioList(FormVal::$bool, ['separator' => FormVal::$separator10]); ?></div>
            </div>
            <div class="row">
                <div class="col-sm-6"><?= $form->field($model, 'is_auto_sale_on')->radioList(FormVal::$bool, ['separator' => FormVal::$separator10]); ?></div>
                <div class="col-sm-6"><?= $form->field($model, 'is_auto_sale_off')->radioList(FormVal::$bool, ['separator' => FormVal::$separator10]); ?></div>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="row">
                <div class="col-sm-6"><?= $form->field($model, 'factory_id')->dropDownList($factorys) ?></div>
            </div>
            <div class="row">
                <div class="col-sm-12"><?= $form->field($model, 'remark')->textarea() ?></div>
            </div>
        </div>
        <div class="clear"></div>
    </div>

    <div id="attr" class="clear goodsItem <?php if($model->goods_type==0):?>none<?php endif;?>">
        <legend>商品属性</legend>
        <div class="row">
            <div class="col-sm-12" id="attr_list">
                <?php
                    if($model->goods_type>0){
                        $goodsType=GoodsType::find()->where('enable=1 and id=:id',[':id'=>$model->goods_type])->one();
                        if($goodsType){
                            echo $this->render('_attr', [
                                'goodsType' => $goodsType,
                                'goodsForm'=>$model,
                            ]);
                        }
                    }  
                ?>
            </div>
        </div>
    </div>

    <div id="product" class="goodsItem">
        <legend>货品列表</legend>
        <div class="row">
            <div class="col-sm-12">
                <div id="product_list">
                    
                </div>
                <div class="help-block"><b>提醒：</b>将光标定位在第一个表单后，可以按键盘上的Tab键,将光标切换到下一个表单，加快操作速度。</div>
            </div>
        </div>
    </div>
    
    <div id="goods_desc" class="goodsItem">
        <legend>商品描述</legend>
        <div class="row">
            <div class="col-sm-12">
            <?php
            $opts=[
                'width'=>'880px',
                'uploadJson'=>Url::to(['/upload/kindeditor']),
            ];
            echo $form->field($model, 'desc')->label(false)->widget(\kitt2000\kindeditor\KindEditorWidget::classname(),['clientOptions'=>$opts]);?>
            </div>
        </div>
    </div>

    <div class="form-group">
        <?= Html::submitButton($model->id>0 ? '更新商品' : '新建商品', ['class' => $model->id>0 ? 'btn btn-primary' : 'btn btn-success']) ?>
    </div>
</div>

<?php ActiveForm::end(); ?>

<div id="attr_img_form"></div>


<?php 
    if($model->goods_type==0){
        $cur=$model->products[0];
        $min=$model->products[0]->mins;
        $prices=$model->products[0]->prices;
    }else{
        $cur=new \common\models\product\Product;
        $min=$cur->mins;
        $prices=$cur->prices;
    }
$i=0;
?>
<div id='one_product_copy'>
    <table cellpadding="1" cellspacing="1">
        <tr class="title">
            <th class="required">货品编号</th>
            <th>国际码</th>
            <th>厂家编号</th>
            <th>短名称(打印条码用)</th>
            <th class="required">成本价</th>
            <th>市场价</th>
            <th>货位</th>
            <th class="required">重量(克)</th>
            <th>零售价</th>
            <th>混批价</th>
            <th>整箱价</th>
        </tr>
        <tr class="product-map-item">
            <td>
                <input type="hidden" name="GoodsForm[products][<?=$i?>][id]" id="product_id_<?=$i?>" value="<?=$cur->id?>" />
                <input type="text" class="product-sn" index="<?=$i?>" name="GoodsForm[products][<?=$i?>][sn]" size="15" value="<?=$cur->sn?>" />
            </td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][sn_intel]" size="15" value="<?=$cur->sn_intel?>" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][sn_purchase]" size="15" value="<?=$cur->sn_purchase?>" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][name_short]" value="<?=$cur->name_short?>" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][price_cost]" value="<?=$cur->price_cost?>" size="7" class="money product-price-cost" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][price_market]" value="<?=$cur->price_market?>" size="7" class="money" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][slot]" value="<?=$cur->slot?>" size="7" /></td>
            <td><input type="text" name="GoodsForm[products][<?=$i?>][weight]" value="<?=$cur->weight?>" size="7" class="money product-weight" /></td>
            <td class="price-step-list">
                <input type="hidden" name="GoodsForm[products][<?=$i?>][type][1][id]" value="<?=$min[1]->id?>" />
                <input type="text" size="7" name="GoodsForm[products][<?=$i?>][type][1][step]" class="format-number" placeholder="递增量" title="递增量" value="<?=$min[1]->step?>" /> 
                <a href="javascript:void(0);" onclick="listPriceStep(this);" title="显示所有价格梯度">+</a>
                <div class="price-step">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][1][prices][0][id]" value="<?php if(isset($prices[1][0]->id)){echo $prices[1][0]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][0][min]" value="<?php if(isset($prices[1][0]->number)){echo $prices[1][0]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][0][price]" value="<?php if(isset($prices[1][0]->price)){echo $prices[1][0]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][1][prices][1][id]" value="<?php if(isset($prices[1][1]->id)){echo $prices[1][1]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][1][min]" value="<?php if(isset($prices[1][1]->number)){echo $prices[1][1]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][1][price]" value="<?php if(isset($prices[1][1]->price)){echo $prices[1][1]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][1][prices][2][id]" value="<?php if(isset($prices[1][2]->id)){echo $prices[1][2]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][2][min]" value="<?php if(isset($prices[1][2]->number)){echo $prices[1][2]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][1][prices][2][price]" value="<?php if(isset($prices[1][2]->price)){echo $prices[1][2]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
            </td>
            <td class="price-step-list">
                <input type="hidden" name="GoodsForm[products][<?=$i?>][type][2][id]" value="<?=$min[2]->id?>" />
                <input type="text" size="7" name="GoodsForm[products][<?=$i?>][type][2][step]" value="<?=$min[2]->step?>" class="format-number" placeholder="递增量" title="递增量" /> 
                <a href="javascript:void(0);" onclick="listPriceStep(this);" title="显示所有价格梯度">+</a>
                <div class="price-step">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][2][prices][0][id]"  value="<?php if(isset($prices[2][0]->id)){echo $prices[2][0]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][0][min]" value="<?php if(isset($prices[2][0]->number)){echo $prices[2][0]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][0][price]" value="<?php if(isset($prices[2][0]->price)){echo $prices[2][0]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][2][prices][1][id]" value="<?php if(isset($prices[2][1]->id)){echo $prices[2][1]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][1][min]" value="<?php if(isset($prices[2][1]->number)){echo $prices[2][1]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][1][price]" value="<?php if(isset($prices[2][1]->price)){echo $prices[2][1]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][2][prices][2][id]" value="<?php if(isset($prices[2][2]->id)){echo $prices[2][2]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][2][min]" value="<?php if(isset($prices[2][2]->number)){echo $prices[2][2]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][2][prices][2][price]" value="<?php if(isset($prices[2][2]->price)){echo $prices[2][2]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
            </td>
            <td class="price-step-list">
                <input type="hidden" name="GoodsForm[products][<?=$i?>][type][3][id]" value="<?=$min[3]->id?>" />
                <input type="text" name="GoodsForm[products][<?=$i?>][type][3][step]" value="<?=$min[3]->step?>" size="7" class="format-number" placeholder="递增量" title="递增量" /> 
                <a href="javascript:void(0);" onclick="listPriceStep(this);" title="显示所有价格梯度">+</a>
                <div class="price-step">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][3][prices][0][id]"  value="<?php if(isset($prices[3][0]->id)){echo $prices[3][0]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][0][min]" value="<?php if(isset($prices[3][0]->number)){echo $prices[3][0]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][0][price]" value="<?php if(isset($prices[3][0]->price)){echo $prices[3][0]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][3][prices][1][id]" value="<?php if(isset($prices[3][1]->id)){echo $prices[3][1]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][1][min]" value="<?php if(isset($prices[3][1]->number)){echo $prices[3][1]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][1][price]" value="<?php if(isset($prices[3][1]->price)){echo $prices[3][1]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
                <div class="price-step none">
                    <input type="hidden" name="GoodsForm[products][<?=$i?>][type][3][prices][2][id]"  value="<?php if(isset($prices[3][2]->id)){echo $prices[3][2]->id;}?>" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][2][min]" value="<?php if(isset($prices[3][2]->number)){echo $prices[3][2]->number;}?>" class="format-number" size="7" placeholder="起订量" title="起订量" />
                    <input type="text" name="GoodsForm[products][<?=$i?>][type][3][prices][2][price]" value="<?php if(isset($prices[3][2]->price)){echo $prices[3][2]->price;}?>" class="money" size="7" placeholder="价格" title="价格" />
                </div>
            </td>
        </tr>
    </table>
</div>

<script>
    window.onload = function () {
        replaceGoodsCategoryContentCopy();
        goods_category_onselect();
        gallery_thumb_onMouseOver();
        pack_unit_init();
        goods_type_change();
        format_init();
        form_beforeSubmit();
        product_sn_change();
        
        <?php if($model->goods_type>0):?>
            $('#product_list').html($('#product_map').html());
            $('#product_map').html('');
            product_init();
        <?php else:?>
            $('#product_list').html($('#one_product_copy').html());
        <?php endif;?>
    };

///////////////商品类目部分///////////////////////////////////
    function closeGoodsCategoryDialog() {
        $("#selectGoodsCategoryDialog .modal-header .close").click();
    }
    
    function goods_category_onselect() {
        $('#btn-category-affirm').addClass('disabled');
        $('.goods-category').unbind('change').change(function () {
            var id = $(this).val();
            var data = 'id=' + id;
            $.ajax({
                url: '<?= Url::to(['get-category']) ?>',
                type: 'POST',
                dataType: 'html',
                data: data,
                success: function (ret) {
                    $('.goods-category-content').html(ret);
                },
            });
        });

        if ($('.goods-category-content .goods-category:last').val() != null) {
            $('#btn-category-affirm').removeClass('disabled');
        }
    }

    //确认选择类目
    function selectGoodsCategory() {
        var categoryId = $('.goods-category-content .goods-category:last').val();
        if (categoryId != null) {
            $('#goodsform-category_id').val(categoryId);
            var str = '';
            var con = '';
            $('.goods-category-content .goods-category').each(function () {
                opt = $(this).find('option:selected').text();
                str = str + con + opt;
                con = ' >> ';
            });

            $('#goods_category_list').html(str);
            closeGoodsCategoryDialog();
        }
    }
    
    ///////////////商品分类部分///////////////////////////////////
    function closeGoodsClassDialog() {
        $("#selectGoodsClassDialog .modal-header .close").click();
    }
    
    function beforeClick(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("tree_class_id");
        zTree.checkNode(treeNode, !treeNode.checked, null, true);
        return false;
    }
		
    function onCheck(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("tree_class_id"),
        nodes = zTree.getCheckedNodes(true),
        ids = "";
        var names='';
        var con='';
        var con2='';
        for (var i=0, l=nodes.length; i<l; i++) {
            ids +=con + nodes[i].id;
            names +=con2 + nodes[i].name;
            con=',';
            con2='，';
        }
        $('#goods_class_list').html(names);
        $('#goodsform-class_id').val(','+ids+',');
    }
    
    ///////////////商品相册///////////////////////////////////
    function galleryMove(index,type){
        if(type==1 && index<=0){
            return false;
        }
        
        if(type==2 && index>=4){
            return false;
        }
        
        var next=type==1?index-1:index+1;

        var tmpPath=$('.gallery-thumb-input').eq(index).val();
        var tmpId=$('.gallery-id').eq(index).val();
        var tmpUrl=$('.gallery-thumb img').eq(index).attr('src');
        
        
        var nextTmpPath=$('.gallery-thumb-input').eq(next).val();
        var nextId=$('.gallery-id').eq(next).val();
        var nextTmpUrl=$('.gallery-thumb img').eq(next).attr('src');
        
        if(type==2 && nextTmpPath==''){
            return false;
        }
        
        if(type==1 && tmpPath==''){
            return false;
        }
        
        $('.gallery-thumb img').eq(index).attr('src',nextTmpUrl);
        $('.gallery-thumb-input').eq(index).val(nextTmpPath);
        $('.gallery-id').eq(index).val(nextId);
        
        $('.gallery-thumb img').eq(next).attr('src',tmpUrl);
        $('.gallery-thumb-input').eq(next).val(tmpPath);
        $('.gallery-id').eq(next).val(tmpId);
    }
    
    function galleryDel(index){
        $('.gallery-thumb img').eq(index).attr('src','');
        $('.gallery-thumb-input').eq(index).val('');
        $('.gallery-id').eq(index).val('');
        checkGalleryNum();
    }
    
    function gallery_thumb_onMouseOver(){
        $('.gallery-thumb .box').mouseover(function(){
            var src=$(this).find('img').attr('src');
            if(src!=''){
                $('#gallery_img img').attr('src',src);
                $(this).find('.toolbar').css('display','block');
            }
            $(this).mouseout(function(){
                $(this).find('.toolbar').css('display','none');
            });
        });
    }
    
    function gallery_onFileTypeError(file){
        alert('文件 \'' + file.name + '\' 不允许上传！');
    }
    
    function gallery_onFileSizeError(file){
        alert('文件 \'' + file.name + '\' 大小超出限制！');
    }
    
    function gallery_onUploadSuccess(id, ret){
        if(ret.result==true){
            $('#gallery_img img').attr('src',ret.content.url);
            setGalleryInput(ret.content.path,ret.content.url);
        }else{
            alert(ret.content.err_msg);
        }
    }
    
    function setGalleryInput(path,url){
        var i=0;
        var isFind=false;
        $('.gallery-thumb-input').each(function(){
            if($(this).val()=='' && isFind==false){
                $('.gallery-thumb img').eq(i).attr('src',url);
                $(this).val(path);
                isFind=true;
            }
            i++;
        });

        checkGalleryNum();
    }
    
    function checkGalleryNum(){
        var count=0;
        $('.gallery-thumb-input').each(function(){
            if($(this).val()!=''){
                count++;
            }
        });

        if(count>=5){
            $('#gallery_mask').removeClass('none');
        }else{
            $('#gallery_mask').addClass('none');
        }
    }
    
    function gallery_onUploadProgress(id, percent){
        var percentStr = percent + '%';
        //update_file_progress(id, percentStr);
    }
    
    function update_file_progress(id, percentStr){
        $('#gallery_progress').html(percentStr+'%');
    }
    
    ////////////////包装单位//////////////////////
    function pack_unit_init(){
        var key='packUnit_<?=$admin->id?>';
        var maxList=8;
        
        setPackUnitList();
        $('#goodsform-pack_unit').blur(function(){
            var unit=$(this).val();
            if(unit!=''){
                var units=$.cookie(key);
                var result=[unit];
                if(units!=undefined && units!=''){
                    var arr=units.split('|');
                    if($.inArray(unit, arr)==-1){
                        result=$.merge( result, arr);
                    }
                }
                
                if(result.length>maxList){
                    result=result.slice(0,maxList);
                }
                $.cookie(key, result.join('|'), { expires: 300, path: '/' });
                
                setPackUnitList();
                packUnit_click();
            }
        });
        
        packUnit_click();
    }
    
    function setPackUnitList(){
        var key='packUnit_<?=$admin->id?>';
        var units=$.cookie(key);
        var str='';
        if(units!=undefined && units!=''){
            var arr=units.split('|');
            for(var i=0;i<arr.length;i++){
                str+='<div>'+arr[i]+'</div>';
            }
        }
        $('#pack_unit_list').html(str);
    }
    
    function packUnit_click(){
        $('#pack_unit_list div').click(function(){
            
            $('#goodsform-pack_unit').val($(this).html());
        });
    }
    
    ////////////////商品类型切换//////////////////////
    function goods_type_change(){
        $('#goodsform-goods_type').change(function(){
            var id = $(this).val();
            var goods_id='<?=$model->id?>';
            if(goods_id==''){
                goods_id=0;
            }

            if(id==0){
                $('#attr').css('display','none');
                $('#attr_list').html('');
                $('#product_list').html($('#one_product_copy').html());
                return ;
            }
            
            var url='<?=  Url::to(['get-type']);?>';
            $.get(url,{typeId:id,goods_id:goods_id},function(ret){
                $('#attr').css('display','block');
                $('#attr_list').html(ret);
                $('#product_list').html($('#product_map').html());
                $('#product_map').html('');
                product_init();
            });
        });
    }
    
    ////////////////货品列表//////////////////////
    //显示价格梯度列表
    function listPriceStep(e){
        var parent=$(e).parent();
        if(parent.find('.price-step:eq(1)').hasClass('none')){
            parent.find('.price-step:eq(1)').removeClass('none');
            parent.find('.price-step:eq(2)').removeClass('none');
        }else{
            parent.find('.price-step:eq(1)').addClass('none');
            parent.find('.price-step:eq(2)').addClass('none');
        }
    }
    
    function form_beforeSubmit(){
        $('#<?= $form->getId() ?>').on('beforeSubmit', function () {
            var goodsType=$('#goodsform-goods_type').val();
            var isBreak=false;
            
            //验证规格
            if(goodsType>0){
                $('.sku-item').each(function(){
                    if(isBreak==true){
                        return;
                    }
                    if($(this).find('.sku-checkbox:checked').length<=0){
                        alert('商品规格未选择！');
                        isBreak=true;
                    }
                });
            }
            if(isBreak===true){
                return false;
            }
            
            //验证货品信息
            $('#product_list tr.product-map-item').each(function(){
                if(isBreak===true)
                    return false;
                
                if(!$(this).hasClass('none')){
                    var product_sn=$(this).find('.product-sn');
                    if($.trim(product_sn.val())==''){
                        alert('货品编号不能为空！');
                        product_sn.focus();
                        isBreak=true;
                        return ;
                    }
                    
                    var price=$(this).find('.product-price-cost');
                    if($.trim(price.val())==''){
                        alert('成本价不能为空！');
                        price.focus();
                        isBreak=true;
                        return ;
                    }
                    
                    var weight=$(this).find('.product-weight');
                    if($.trim(weight.val())==''){
                        alert('货品重量不能为空！');
                        weight.focus();
                        isBreak=true;
                        return ;
                    }
                }
            });
            
            if(isBreak===true){
                return false;
            }else{
                //清空无效的提交表单
                $('.sku-img-list tr.none td').empty();
                $('#product_list tr.none td').empty();
                
                $('.sku-checkbox').each(function(){
                    if(!$(this).is(':checked')){
                        var attr_id=$(this).attr('attr_id');
                        var index=$(this).attr('index');
                        
                        $('#sku_id_'+attr_id+'_'+index).empty();
                        $('#sku_aliases_'+attr_id+'_'+index).empty();
                        $('#sku_img_'+attr_id+'_'+index).empty();
                    }
                });
                return true;
            }
      });
    }
    
    function replaceGoodsCategoryContentCopy(){
        $('#goods_category_content').html($('#goods_category_content_copy').html());
        $('#goods_category_content_copy').html('');
    }
    
    function product_sn_change(){
        $('.product-sn').blur(function(){
            var e=this;
            var index=$(e).attr('index');
            var val=$.trim($(e).val());
            var product_id=$('#product_id_'+index).val();
            
            if(val=='')
                return ;
            
            //检测表单内是否有重复
            $('.product-sn').each(function(){
                var index2=$(this).attr('index');
                var val2=$.trim($(this).val());
                if(index!=index2 && val==val2){
                    $(e).val('').focus();
                    alert('货品编号重复！');
                    return ;
                }
            });
            
            var url='<?=  Url::to(['check-product-sn']);?>';
            $.getJSON(url,{'sn':val,product_id:product_id},function(ret){
                if(ret.result==false){
                    $(e).val('');
                    alert(ret.content.msg);
                }
            });
        });
    }
</script>




<?php
function getList($arr, $selected = [], &$out = []) {
    foreach ($arr as $item) {
        $t = ['id' => $item['id'], 'pId' => $item['parent_id'], 'name' => $item['name']];
        if (count($item['child']) > 0) {
            $t['open'] = true;
            $t['nocheck'] = true;
        } else {
            if (!empty($selected) && in_array($t['id'], $selected)) {
                $t['checked'] = true;
            }
        }

        $out[] = $t;
        if (count($item['child']) > 0) {
            getList($item['child'], $selected, $out);
        }
    }
    return $out;
}
?>